package com.financing.service.invest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.financing.enums.invest.CouponRule;
import com.financing.enums.invest.InvestLogType;
import com.financing.enums.notify.AgentNotify;
import com.financing.enums.notify.AssetsNotify;
import com.financing.model.Data;
import com.financing.model.invest.Bid;
import com.financing.model.invest.Coupon;
import com.financing.model.invest.CouponLog;
import com.financing.model.user.User;
import com.financing.service.BaseService;
import com.financing.service.system.AssetsLogService;
import com.financing.util.DateUtil;
import com.financing.util.Money;
import com.financing.util.Str;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class CouponService extends BaseService<Bid>{
	private AssetsLogService assetsLog = new AssetsLogService();	
    private static final Logger logger = Logger.getLogger(CouponService.class);

	/**
	 * 分页信息
	 * @param map 
	 * @return
	 */
	public Page<Coupon> list(int page, int size, Map<String, String> map) {
		return Coupon.me.paginate(page, size, buildSql("coupon",Arrays.asList("rule","name", "type", "status"),map));
	}

	/**
	 * 根据名称获取数据
	 */
	public Coupon findByName(String name) {
		return Coupon.me.findFirst("select id from coupon where name='"+name+"' ");
	}
	
	/**
	 * 获取可用的优惠券
	 * @return
	 */
	public void available(int userId, String rule) {
		this.available(userId, rule, 0, 0);
	}
	
	/**
	 * 获取可用的优惠券
	 * @return
	 */
	public void available(int userId, String rule, double amt) {
		this.available(userId, rule, amt, 0);
	}
	
	/**
	 * 获取可用的优惠券
	 * @return
	 */
	public void available(int userId, String rule, double target, int item) {
		
		String time = DateUtil.getNowDateAndTime();
		User u = User.me.findById(userId);
		List<Coupon> list = Coupon.me.find("select * from coupon where rule=? AND status='enable' AND start_time<=? AND end_time>=?", rule, time, time);
		
		for(Coupon c : list){ 
					
			// 判断优惠券是否可以重复领取
			if(c.getIsRepeat()==0){
				CouponLog cl = CouponLog.me.findFirst("select * from coupon_log where user_id=? AND coupon_id=?", userId, c.getId());
				if(cl!=null && cl.getId()>0){
					logger.error(c.getId()+c.getName()+"优惠券不可重复领取");
					continue;
				}
			}
			CouponLog log = new CouponLog();
			log.setUserId(userId);
			log.setStatus("normal");
			log.setCouponId(c.getId());
			log.setLimitAmount(c.getLimitAmount());
			if(c.getValidDay()>0){
				Date now = new Date();
				log.setValidStartTime(now);
				log.setValidEndTime(DateUtil.adjust(now, c.getValidDay()));
			}else{
				log.setValidStartTime(c.getValidStartTime());
				log.setValidEndTime(c.getValidEndTime());
			}
			log.setIsShow(1);
			log.setType(c.getType());
			log.setLink(c.getLink());
			log.setMobile(u.getMobile());
			log.setRealName(u.getRealName());
			double last = 0.0;
			double t = 0.0;
			double amount = 0.0;
			if(Str.eq(CouponRule.REG, rule) || Str.eq(CouponRule.REAL, rule)){	// 注册 & 实名
				log.setAmount(Integer.valueOf(c.getRuleAmount()));
				// 实名更新记录
				if(Str.eq(CouponRule.REAL, rule)) {
					Db.update("update coupon_log set real_name=? where user_id=?",u.getRealName(),u.getId());
					Db.update("update logger set real_name=? where user_id=?",u.getRealName(),u.getId());
				}
			}else if(Str.eq(CouponRule.DEPOSIT, rule) || Str.eq(CouponRule.TRADE, rule)) {		// 充值 & 投资
				Bid b = null;
				/**if(Str.eq(CouponRule.TRADE, rule)) {
					Trade td = Trade.me.findById(item);
					b = Bid.me.findById(td.getBidId());
					if(Str.eq(CouponRule.TRADE, rule)){
						if(td!=null && td.getJxq()>0 && Str.eq("jxq", log.getType())) {
							continue;
						}
						if(td!=null && td.getTyj()>0 && Str.eq("tyj", log.getType())) {
							continue;
						}
						if(td!=null && td.getTzhb()>0 && Str.eq("tzhb", log.getType())) {
							continue;
						}
					}
				}*/
				
				// 判断是否为对应的标的（充值不限）
				if(Str.eq(CouponRule.DEPOSIT, rule) 
					|| (b!=null && Str.eq(CouponRule.TRADE, rule) && (StringUtils.contains(c.getRuleBid(), ","+b.getType()+",") || (Str.eq("public", b.getType()) && StringUtils.contains(c.getRuleBid(), ","+b.getDayLimit()+"day,"))))){
					// 判断投资金额是否达标
					JSONObject json = JSON.parseObject(c.getRuleAmount());	
					String increase = json.getString("increase");
					if(Str.eq(increase, "1")) {
						t = json.getDouble("target");
						amount = json.getDouble("amount");
						last = Money.mul((int) Money.div(target, t), amount);
					}else if(Str.eq(increase, "0")) {
						JSONArray amounts = JSON.parseArray(json.getString("amounts"));
						for(int i=0;i<amounts.size();i++){
							JSONObject j = amounts.getJSONObject(i);
							if(j.getDouble("amount")>last && target >=j.getDouble("target")){
								last = j.getDouble("amount"); 
							}
						}
					}
					log.setAmount((int)last);
				} else {
					continue;
				}
			} else if(Str.eq(CouponRule.EXCHANGE, rule)){	// 积分兑换
				if(c.getId()==(int) target) {
					log.setAmount(Integer.valueOf(c.getRuleAmount()));
				}else {
					continue;
				}
			} else {
				log.setAmount(0);
			}
			
			// 设置最低限额
			if(Str.eq("tyj", c.getType())) {
				log.setLimitAmount(c.getLimitAmount());
			} else { 
				JSONObject json = JSON.parseObject(c.getLimitAmount());	
				t = json.getDouble("target");
				String increase = json.getString("increase");
				if(Str.eq(increase, "1")) {
					amount = json.getDouble("amount");
					last = Money.mul((int) Money.div(log.getAmount(), amount), t);
				}else{
					last = t;
				} 
				log.setLimitAmount(String.valueOf(last));
			}
			/** else if(Str.eq(CouponRule.RECOMMEND, rule)){	// 好友推荐
				JSONObject json = JSONObject.parseObject(c.getStr("rule_amount"));
				int min = json.getInteger("min");
				int max = json.getInteger("max");
				Random random = new Random();
			    int s = random.nextInt(max-min+1)+min;  
				log.setAmount(Double.valueOf(s));
			} */
			log.setCreateTime(new Date());
			log.setAllowBid(c.getAllowBid());
			log.setAccess(c.getRule());

			amount = log.getAmount();
			double left = Money.sub(c.getNum(), c.getApplyNum());
			
			if(amount>0){
				// 判断可领取的优惠券是否超过额度
				if(left>=1){
					c.setApplyNum(Money.add(c.getApplyNum(), 1.0)).update();
				}else{
					logger.error(c.getId()+c.getName()+"加息券优惠券数量不足！");
					continue;
				}
				if(c.getApplyNum()>=c.getNum()){
					c.setStatus("finish");
				}
				log.save();
				
				String access = "注册";
				switch(log.getAccess()){
					case CouponRule.DIRECT : access = "定向"; break;
					case CouponRule.DEPOSIT : access= "充值"; break;
					case CouponRule.TRADE : access = "投资"; break;
					case CouponRule.REAL : access = "实名"; break;
					case CouponRule.BIRTHDAY : access = "生日"; break;
					case CouponRule.EXCHANGE : access = "积分兑换"; break;
				}
				// 获取优惠券名称
				String couponName= log.getName();
				

				// 发送用户资产信息提醒
				AssetsNotify assets = Str.ne(CouponRule.BIRTHDAY, log.getAccess()) ? AssetsNotify.COUPON : AssetsNotify.COUPON_BIRTHDAY;
				AgentNotify agentNotify = Str.ne(CouponRule.BIRTHDAY, log.getAccess()) ? AgentNotify.COUPON : AgentNotify.COUPON_BIRTHDAY;
				assetsLog.bulid(u, Str.format(assets.getName(), access+couponName), Str.format(assets.getContents(), access, couponName), Str.format(agentNotify.getContents(), u.getMobile()+"（"+u.getRealName()+"）", access, couponName));

				// 插入交易记录
				if(Str.eq("tyj", log.getType())) {
					InvestLogService.build("体验金", InvestLogType.TYJ, log.getId(), amount, u.getId(), "success", "体验金奖励", "");
				}
				
				/** 发送获取优惠券短信（注册不需要发送短信）
				int days = DateUtil.diff(new Date(), log.getValidEndTime());
				if(Str.ne(CouponRule.REG, log.getAccess())) {
					Sms.send(u.getMobile(), Str.format(SmsNotify.ACHIEVE, couponName, days));
				}*/
			}
		}
	}

	public void updateExpired() {
		String time = DateUtil.getNowDateAndTime();
		Db.update("UPDATE coupon SET status='auto' WHERE status='enable' AND end_time<=? ", time);
	}
	
	public void transTagName(Coupon c) {
		Map<String,String> allowBidMap = 
			Data.putStr("public","常规标","first","新手标","experi","体验标","30day","1月标","45day","45天标","60day","2月标","90day","3月标","180day","6月标","210day","7月标","360day","12月标");
		String v = "";
		if(Str.nb(c.getAllowBid())){
			for(String key : c.getAllowBid().split(",")){
				if(StringUtils.isNotBlank(key)){
					v += allowBidMap.get(key)+"、";
				}
			}
			c.setAllowBid(v.length()>0 ?v.substring(0, v.length()-1)+"可用":v);
			v = "";
			for(String key : c.getRuleBid().split(",")){
				if(StringUtils.isNotBlank(key)){
					v += allowBidMap.get(key)+"、";
				}
			}
			c.setRuleBid(v.length()>0 ?v.substring(0, v.length()-1)+"可用":v);
		}
	}
}
